const {
  MenuNotFoundError,
  HasChildMenuError,
} = require('../../domain/menu/error')
const Usecase = require('../../shared/usecase/Usecase')

class DeleteMenu extends Usecase {
  constructor({ menuRepo, database, currentUser }) {
    super()
    this.menuRepo = menuRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }
  async execute(id) {
    const menu = await this.menuRepo.findById(id)
    if (!menu) throw new MenuNotFoundError(id)
    const children = await this.menuRepo.findAll({
      parentId: id,
    })
    if (children.length) {
      throw new HasChildMenuError(menu.name)
    }
    const transaction = await this.sequelize.transaction()
    try {
      await this.menuRepo.remove(menu, {
        transaction,
        currentUser: this.currentUser,
      })
      await transaction.commit()
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = DeleteMenu
